package niu_ke.lianbiao.bm02_链表内指定区间反转;

/**
 * @author： YHSimon
 * @date： 2022-07-10 14:17
 */

class ListNode {
    int val;
    ListNode next = null;

    public ListNode(int val) {
        this.val = val;
    }
}

public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode preHead = new ListNode(0);
        preHead.next = head;
        ListNode preStart = preHead;
        ListNode start = head;

        for (int i = 1; i < m; i++) {
            preStart = start;
            start = start.next;
        }

        // reverse
        for (int i = 0; i < n - m; i++) {
            ListNode tmp = start.next;
            start.next = tmp.next;
            tmp.next = preStart.next;
            preStart.next = tmp;
        }
        return preHead.next;
    }

    public static void main(String[] args) {
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        ListNode n5 = new ListNode(5);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        Solution s = new Solution();
        System.out.println(s.reverseBetween(n1, 2, 4));


    }
}
